<template>
  <div class="comment-section">
    <div class="comment-list">
      <div v-for="comment in comments" :key="comment.id" class="comment-item">
        <el-avatar :src="comment.avatar || '/default-avatar.png'" :size="40" />
        <div class="comment-content">
          <div class="comment-header">
            <span class="username">{{ comment.username }}</span>
            <span class="time">{{ formatTime(comment.createTime) }}</span>
          </div>
          <div class="comment-text">{{ comment.content }}</div>
        </div>
        <!-- 如果是当前用户的评论，显示删除按钮 -->
        <el-button
          v-if="userInfoStore.info.id === comment.userId"
          type="danger"
          link
          @click="handleDelete(comment.id)"
        >
          删除
        </el-button>
      </div>
      <div v-if="comments.length === 0" class="no-comments">
        暂无评论，来发表第一条评论吧！
      </div>
    </div>
    
    <div class="comment-input">
      <el-input
        v-model="newComment"
        type="textarea"
        :rows="2"
        placeholder="写下你的评论..."
        @keyup.enter.native="submitComment"
      />
      <el-button type="primary" @click="submitComment" :disabled="!newComment.trim()">
        发表评论
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { addComment, getComments, deleteComment } from '@/api/comment'
import { ElMessage, ElMessageBox } from 'element-plus'
import useUserInfoStore from '@/stores/userInfo'

const props = defineProps({
  lessonId: {
    type: Number,
    required: true
  }
})

const userInfoStore = useUserInfoStore()
const comments = ref([])
const newComment = ref('')

// 获取评论列表
const fetchComments = async () => {
  try {
    const res = await getComments(props.lessonId)
    if (res.code === 0) {
      comments.value = res.data
    } else {
      ElMessage.error(res.msg || '获取评论失败')
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败，请稍后重试')
  }
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) return
  
  try {
    const commentData = {
      lessonId: props.lessonId,
      userId: userInfoStore.info.id,
      content: newComment.value.trim(),
      username: userInfoStore.info.username,
      avatar: userInfoStore.info.userPic || ''
    }
    
    const res = await addComment(commentData)
    if (res.code === 0) {
      ElMessage.success('评论成功')
      newComment.value = ''
      await fetchComments()
    } else {
      ElMessage.error(res.msg || '评论失败')
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('评论失败，请重试')
  }
}

// 删除评论
const handleDelete = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteComment(commentId)
    if (res.code === 0) {
      ElMessage.success('删除成功')
      await fetchComments()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchComments()
})
</script>

<style scoped>
.comment-section {
  margin-top: 20px;
}

.comment-list {
  margin-bottom: 20px;
}

.comment-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-content {
  margin-left: 12px;
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.username {
  font-weight: bold;
  color: #333;
}

.time {
  color: #999;
  font-size: 12px;
}

.comment-text {
  color: #666;
  line-height: 1.6;
  word-break: break-all;
}

.comment-input {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.comment-input .el-button {
  align-self: flex-end;
}

.no-comments {
  text-align: center;
  color: #999;
  padding: 20px 0;
}
</style> 